package com.hello.Launcher;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class CommunicationMgr {
	private static final String serverURL ="http://drunkoid.appspot.com/";
	private static final String localURL ="http://localhost:8888/";	
	private static String url = serverURL;

	public static void setUrl(boolean local){
		url = local ? localURL : serverURL;
	}

	public static int sendLocation(String id, double longitude, double latitude) {
		int retval = 0;
		try{
			URLConnection con = getServletConnection("update-location?id="+id+
					"&longitude="+longitude+
					"&latitude="+latitude);
			if (con != null){
				// send data to the servlet
				OutputStream outstream = con.getOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(outstream);
				oos.writeObject("");
				oos.flush();
				oos.close();
				InputStream instr = con.getInputStream();
				ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
				retval = (Integer) inputFromServlet.readObject();
				inputFromServlet.close();
				instr.close();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return retval;
	}
	
	public static int isNearCluster(String id, double longitude, double latitude){
		int retval = 0;
		try{
			URLConnection con = getServletConnection("check-surround?id="+id+
					"&longitude="+longitude+
					"&latitude="+latitude);
			if (con != null){
				// send data to the servlet
				OutputStream outstream = con.getOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(outstream);
				oos.writeObject("");
				oos.flush();
				oos.close();
				InputStream instr = con.getInputStream();
				ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
				retval = (Integer) inputFromServlet.readObject();
				inputFromServlet.close();
				instr.close();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return retval;
	}

	private static URLConnection getServletConnection(String servletPostfix)
	throws MalformedURLException, IOException {
		URL urlServlet = new URL(url + servletPostfix);
		URLConnection con = urlServlet.openConnection();
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestProperty("Content-Type","text/html");
		return con;
	}
}
